import os
from uuid import uuid4
from flask import Flask, request, render_template
from flask_restful import Api, Resource, reqparse
from werkzeug.datastructures import FileStorage
import datetime

app = Flask(__name__)
api = Api(app)


APP_ROOT = os.path.dirname(os.path.abspath(__file__))

IMAGE_EXTENSIONS = set(['jpg', 'JPG', 'jpeg','JPEG','png', 'bmp', 'PNG', 'BMP', 'tif', 'TIF'])
VIDEO_EXTENSIONS = set(['mp4', 'MP4'])

@app.route('/')
def index():
    forder="pictures"
    filenames = sorted(os.listdir('./static/images/'+forder))
    image_names=[]
    video_names=[]
    for filename in filenames:  
        if filename.split('.')[-1] in IMAGE_EXTENSIONS:  
            image_names.append(filename)
        if filename.split('.')[-1] in VIDEO_EXTENSIONS:  
            video_names.append(filename)
    # print(image_names)
    return render_template("view.html", image_names=image_names, video_names=video_names, sdate=forder)

@app.route('/getdate', methods=['GET', 'POST'])
def getdate():
    forder="pictures"
    filenames = sorted(os.listdir('./static/images/'+forder))
    image_names=[]
    video_names=[]
    for filename in filenames:  
        if filename.split('.')[-1] in IMAGE_EXTENSIONS:  
            image_names.append(filename)
        if filename.split('.')[-1] in VIDEO_EXTENSIONS:  
            video_names.append(filename)
    if request.method == 'POST':
        sel_date=request.form['date']
        # print(sel_date)
        target = os.path.join(APP_ROOT, './static/images/'+sel_date)
        if os.path.exists(target):
            image_names=[]
            video_names=[]
            filenames = sorted(os.listdir(target))
            for filename in filenames:  
                if filename.split('.')[-1] in IMAGE_EXTENSIONS:  
                    image_names.append(filename)
                if filename.split('.')[-1] in VIDEO_EXTENSIONS:  
                    video_names.append(filename)
            if(len(image_names)==0 and len(video_names)==0):
                image_names = sorted(os.listdir('./static/images/'+forder))
                video_names = []
            else:
                forder=sel_date
    return render_template("view.html", image_names=image_names, video_names=video_names, sdate=forder)

@app.route('/getalbum', methods=['GET'])
def getalbum():
    forder="album"
    filenames = sorted(os.listdir('./static/images/'+forder))
    image_names=[]
    video_names=[]
    for filename in filenames:  
        if filename.split('.')[-1] in IMAGE_EXTENSIONS:  
            image_names.append(filename)
        if filename.split('.')[-1] in VIDEO_EXTENSIONS:  
            video_names.append(filename)
    return render_template("view.html", image_names=image_names, video_names=video_names, sdate=forder)

class UploadAlbum(Resource):
    def post(self):
        forder="album"
        target = os.path.join(APP_ROOT, './static/images/'+forder)
        parser = reqparse.RequestParser()
        parser.add_argument('file', type=FileStorage, location='files')
        args = parser.parse_args()
        file = args['file']
        extension = os.path.splitext(file.filename)[1]
        f_name = str(uuid4()) + extension
        # f_name = file.filename
        if not os.path.exists(target):
            os.mkdir(target)
        destination = "/".join([target, f_name])
        file.save(destination)

        return file.name, 201

class Upload(Resource):
    def post(self):
        today=datetime.date.today()
        target = os.path.join(APP_ROOT, './static/images/'+str(today))
        parser = reqparse.RequestParser()
        parser.add_argument('file', type=FileStorage, location='files')
        args = parser.parse_args()
        file = args['file']
        # extension = os.path.splitext(file.filename)[1]
        # f_name = str(uuid4()) + extension
        f_name = file.filename
        if not os.path.exists(target):
            os.mkdir(target)
        destination = "/".join([target, f_name])
        file.save(destination)

        return file.name, 201

api.add_resource(Upload, '/upload')
api.add_resource(UploadAlbum, '/uploadalbum')

if __name__ == "__main__":
    app.run(port=8006, host='0.0.0.0', debug=False)
